<?php

namespace mpend\models;

use Yii;
use yii\base\Exception;
use mpend\models\User;
use common\models\user\UserMeta;
use common\models\user\UserConnect;

/**
 * 微信小程序接口访问授权接口
 * AuthWechatForm
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class WechatConnectForm extends \common\base\Model {

    /**
     * @var string 应用ID
     */
    public $client;

    /**
     * @var string 时间戳
     */
    public $openid;

    /**
     * @var string 客户端操作系统
     */
    public $unionid;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['client', 'openid'], 'required'],
            [['openid', 'unionid'], 'string', 'max' => 64],
            [['client'], 'in', 'range' => UserConnect::getConstants('client'), 'message' => '{attribute}不在允许范围内'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'client' => '授权应用',
            'openid' => 'OpenId',
            'unionid' => 'UnionId',
        ];
    }

    /**
     * 自动注册操作
     * @inheritdoc
     */
    public function register() {
        if (!$this->validate()) {
            return $this->dumpError('授权参数校验失败', null, 401);
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $connect = UserConnect::findOrNew($this->attributes);
            if ($connect->isNewRecord || !$connect->user_id) {
                $user = new User();
                $user->setUsernameByOpenid(UserConnect::CLIENT_MP, $this->openid);
                $user->generateAuthKey();
                $user->setDefaultAttributes();

                $meta = new UserMeta();
                if (!$user->save()) {
                    throw new Exception('账号注册失败');
                }
                $meta->user_id = $user->id;
                if (!$meta->save()) {
                    throw new Exception('用户信息保存失败');
                }
                $connect->user_id = $user->id;
            }
            if (!$connect->save()) {
                throw new Exception('连接信息保存失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return $this->dumpError($e->getMessage(), null, 401);
        }
        return $connect->user;
    }

}
